<?php
namespace Home\Controller;
use Think\Controller;
use Think\Page;
class MessageController extends Controller{
    /**
     * 发布留言页面
     */
    public function add(){
        if(!session('?user_id')){
            $this->redirect('Home/User/login');
        }
        $this->display();
    }

    /**
     * 发布留言操作
     */
    public function publish(){
        if(!session('?user_id')){
            $this->redirect('Home/User/login');
        }
        $data = [];
        $data['name'] = session('user_name');
        $data['email'] = session('user_email');
        $data['tel'] = session('user_tel');
        $data['content'] = I('post.content', '');
        $data['publish_time'] = time(); // 获取当前时间
        if(empty($data['content'])){
            $this->error('内容不能为空');
        }
        $Message = D('Message');
        if($Message->publish($data)){
            $this->success('发布成功', U('Home/Message/show'));
        }else{
            $this->error('发布失败');
        }
    }

    /**
     * 展示留言页面
     */
    public function show(){
        $sort_by = I('get.sort', 'id');
        $Message = D('Message');
        $count = $Message->count();
        $Page = new Page($count, 5);
        $show = $Page->show();
        $result = $Message->order($sort_by)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('messages', $result);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 搜索
     */
    public function search(){
        $key = I('get.key');
        // TODO 根据key搜索结果并显示
        // sql like
    }
}
